<?php
class AdminAction extends Action {

    public function  __construct() {
        parent::__construct();
        $this->assign('domain',HTTP_DOMAIN);
    }

	public function check(){
        if(!$_SESSION['admin_user_id']){
            $this->assign('jumpUrl','index');
            $this->error('您还未登录!');die();
        }
		
	}

    /**
     * 退出程序
     */
    public function logout(){
        $_SESSION=array();
        session_destroy();
        $this->assign('jumpUrl','index');
        $this->success('成功退出!');
    }

    /**
     * 显示假期情况
     */
    public function showh() {
		$this->assign('alltype','showh');
		$this->check();
        if($uid=intval($_GET['user_id'])) {
			$this->assign('allmap','user_id='.$uid);
            $a=D('LeaveTotal')->getLeaveTotalRemain(30,'user_id ASC',' AND user_id='.$uid);
        }else {
			$this->assign('allmap','1=1');
            $a=D('LeaveTotal')->getLeaveTotalRemain(30);
        }
        $this->assign('pager',$a['0']);
        $this->assign('list',$a[1]);
		$this->assign('totalcount',$a[2]);
        $this->display();
    }

    /**
     * 登录
     */
    public function index() {

        $this->display();
    }

    /**
     * 用户登录后的页面
     */
    public function member() {
		$this->check();
        //获取管理员列表
        $this->assign('adminlist',D('AdminUser')->select());
        $this->display();
    }

    /**
     * 删除一个管理员
     */
    public function delete(){
		$this->check();
        $_SESSION['admin_user_id']==1 || $this->error('只有创始人可以删除用户!');
        $admin_user_id=$_GET['admin_user_id'];
        if($admin_user_id==1){
            $this->error('不能删除创始人的用户!');
        }
        if(D('AdminUser')->delete($admin_user_id)){
            $this->success('删除成功!');
        }
        $this->error('删除失败!');
    }

    /**
     * 更改用户密码
     */
    public function chpwd(){
		$this->check();
        $padmin_user_id=$_GET['admin_user_id'];
        $admin_user_id=$_SESSION['admin_user_id'];
        if($_SESSION['admin_user_id']!=1&&$padmin_user_id!=$admin_user_id){
            $this->error('没有权限操作此项!');
        }
        //获取用户的信息
        $u=D('AdminUser')->find($admin_user_id);
        if(!$u){
            $this->error('获取用户信息失败!');
        }
        $this->assign('user',$u);
        $this->display();
    }

    /**
     * 修改密码
     */
    public function doChpwd(){
		$this->check();
        $padmin_user_id=$_POST['admin_user_id'];
        $admin_user_id=$_SESSION['admin_user_id'];
        if($_SESSION['admin_user_id']!=1&&$padmin_user_id!=$admin_user_id){
            $this->error('没有权限操作此项!');
        }
        if($_POST['admin_pass']!=$_POST['admin_pass_repeat']){
            $this->error('两次输入的密码不一致!');
        }
        if(empty($_POST['admin_pass'])){
            $this->error('密码不能为空!');
        }
        $data=array(
            'admin_pass'=>md5($_POST['admin_pass']),
            'admin_user_id'=>$admin_user_id
        );
        if(D('AdminUser')->save($data)){
            $this->success('更新密码成功!');
        }
        $this->error('更新失败或者未做任何修改!');
    }

    /**
     * 添加一个管理员
     */
    public function doAdduser(){
		$this->check();
        $add_time=date('Y-m-d H:i:s');
        if($_POST['admin_pass']!=$_POST['admin_pass_repeat']){
            $this->error('两次输入的密码不一致!');
        }
        $map=array(
            'admin_username'=>$_POST['admin_username']
        );
        if(M('AdminUser')->where($map)->find()){
            $this->error('已经存在相同的用户名!');
            die();
        }
        $data=array(
            'admin_username'=>$_POST['admin_username'],
            'admin_pass'=>md5($_POST['admin_pass']),
            'add_time'=>$add_time
        );
        if(empty($_POST['admin_username'])||empty($_POST['admin_pass'])){
            $this->error('用户名或者密码不能为空!');
        }
        if(M('AdminUser')->add($data)){
            $this->assign('jumpUrl','member');
            $this->success('添加新的管理员成功!');
        }
        $this->error('添加新的管理员失败!');
    }

    /**
     * 展示导入更新假期
     */
    public function import() {
		$this->check();
        $this->display();
    }

    /**
     * 所有用户列表
     */
    public function allusers() {
		$this->assign('alltype','allusers');
		$this->check();
		$this->assign('allmap','1=1');
        $a=D('User')->getUserList(30);
        $this->assign('pager',$a['0']);
        $this->assign('list',$a[1]);
		$this->assign('totalcount',$a[2]);
        $this->display();
    }

    /**
     * 搜索用户
     */
    public function searchUsers() {
		$this->assign('alltype','search');
		$this->check();
        $this->assign('m','search');
        $map=array_filter($_POST);
        unset($map['__hash__']);
        if($uid=intval($_GET['leader_user_id'])){
            $map['leader_user_id']=$uid;
        }
        if(empty($map)) {
            $this->error('搜索条件不能为空!');
        }
        $list=D('User')->where($map)->select();
        foreach($list as &$v){
            $user_id=$v['user_id'];
            $m['leader_user_id']=$user_id;
            $sslist=D('User')->where($m)->findAll();
            if($sslist){
                $v['ss']=true;
            }else{
                $v['ss']=false;
            }
            unset($v);
        }
        $this->assign('list',$list);
        $this->display('allusers');
    }

    /**
     * 搜索假期总数
     */
    public function searchh() {
		$this->assign('alltype','search');
		$this->check();
        $this->assign('m','search');
        $map=array_filter($_POST);
        unset($map['__hash__']);
        if(empty($map)) {
            $this->error('搜索条件不能为空!');
        }
        $list=D('LeaveTotal')->where($map)->select();
        $this->assign('list',$list);
		$this->assign('totalcount',$a[2]);
        $this->display('showh');
    }

    /**
     * 搜索假期总数
     */
    public function searchlogs() {
		$this->assign('alltype','search');
		$this->check();
        $this->assign('m','search');
        $map=array_filter($_POST);
        unset($map['__hash__']);
        if(empty($map)) {
            $this->error('搜索条件不能为空!');
        }
        $list=D('LeaveLog')->where($map)->select();
        $this->assign('list',$list);
		$this->assign('totalcount',$a[2]);
        $this->display('showlogs');
    }

    /**
     * 展示请假历史记录
     */
    public function showlogs() {
		
		$this->check();
        if($uid=intval($_GET['user_id'])) {
			$this->assign('alltype','logsuser');
			$this->assign('allmap','user_id='.$uid);
            $a=D('LeaveLog')->getLogs(30,'user_id ASC',' AND user_id='.$uid);
        }else {
			$this->assign('allmap','1=1');
			$this->assign('alltype','logsall');
            $a=D('LeaveLog')->getLogs(30);
        }
        
        $this->assign('pager',$a['0']);
        $this->assign('list',$a[1]);
		$this->assign('totalcount',$a[2]);
        $this->display();
    }


    /**
     * 导入假期
     */
    public function doImport() {
		$this->check();
        $type=$_POST['iType'];
        //首先要上传图片，如果上传不成功则不保存
        if (is_uploaded_file($_FILES['F1']['tmp_name'])) {
            import("ORG.Net.UploadFile");
            $uploadObj = new UploadFile();
            $uploadObj->maxSize = 2000000;
            $uploadObj->autoSub = TRUE;
            $uploadObj->subType = 'date';
            $uploadObj->saveRule = 'uniqid';
            $uploadObj->allowExts = array('csv');
            $uploadObj->savePath = ROOT_PATH . '/Public/UploadFiles/';
            if ($uploadObj->upload()) {
                $info = $uploadObj->getUploadFileInfo();
                $path = $info[0]['savepath'];
                $name = $info[0]['savename'];
            } else {
                $this->error('文件上传失败,只允许CSV格式的文件!');
            }
        }

		//法语版本
		$s=file_get_contents($path.$name);
		$s=str_replace(',',' ',$s);
		$s=str_replace(';',',',$s);
		file_put_contents($path.$name,$s);


        $fp=fopen($path.$name,'r');
        if(!$fp) {
            $this->error('读取文件失败!');
        }
        $i=0;
        while($data=fgetcsv($fp)) {
            if($type=='user'&&$i!=0) {
                $user_id=$data[0];
                $first_name=$data[1];
                $last_name=$data[2];
                $leader_id=$data[10];
                D('User')->insertUser($user_id,$first_name,$last_name,$leader_id);
                $this->assign('jumpUrl','allusers');
            }

            if($type=='total'&&$i!=0) {
                $user_id=$data[0];
                $ttype=$data[4];
                $total=$data[7];
                $remain=$data[8];
                $first_name=$data[1];
                $last_name=$data[2];
                D('LeaveTotal')->insertUserTotal($user_id,$ttype,$total,$remain,$first_name,$last_name);
                $this->assign('jumpUrl','showh');
            }

            if($type=='logs'&&$i!=0) {
                $user_id=$data[6];
                $debut=$data[0];
                $fin=$data[1];
                $jours=$data[7];
                $ttype=$data[5];
                $first_name=$data[2];
                $last_name=$data[3];
                D('LeaveLog')->insertLog($user_id,$debut,$fin,$ttype,$jours,$first_name,$last_name);
                $this->assign('jumpUrl','showlogs');
            }
            $i++;
        }
        $this->assign('waitSecond',10);
        $this->success('上传成功!');
    }

    /**
     * 处理用户登录
     */
    public function doLogin() {
        $_SESSION['user_id']=0;
        $username=$_POST['admin_username'];
        $password=$_POST['admin_pass'];
        $u=D('AdminUser')->checkUserPassword($username,$password);
        $this->assign('waitSecond',10);
        if($u) {
            $_SESSION['admin_user_id']=$u;
            $_SESSION['admin_username']=$username;
            $this->assign('jumpUrl','member');
            $this->success('登录成功!');
        }else {
            $this->error('登录失败!');
        }
    }


	public function clear(){
		$this->check();
		if($_GET['type']=='user'){
			$query="truncate table "."gbday_user";
			D('User')->execute($query);
		}
		if($_GET['type']=='log'){
			$query="truncate table "."gbday_leave_log";
			D('User')->execute($query);
		}
		if($_GET['type']=='total'){
			$query="truncate table "."gbday_leave_total";
			D('User')->execute($query);
		}
		if($_GET['type']=='all'){
			$query="truncate table "."gbday_leave_total";
			D('User')->execute($query);
			$query="truncate table "."gbday_leave_log";
			D('User')->execute($query);
			$query="truncate table "."gbday_user";
			D('User')->execute($query);
		}
		$this->success('清空数据库成功!');
	}


	public function exporter(){
		
			$arr=$_POST['checkbox'];
			if(empty($arr)){
				$this->error('Empty!');
			}
			$arr=array_filter($arr);
			$str=implode(',',$arr);
			$map=" id in ($str)";
			if($_POST['expall']==1&&$_POST['alltype']!='search'){
				$map=$_POST['allmap'];
			}
			if($_POST['type']=="showh"){
				echo 'Matricule;Nom;Prénom;ssType;Nombre;Décpte;'."\r\n";
				$r=D('LeaveTotal')->where($map)->findAll();
			}
			if($_POST['type']=="showlogs"){
				echo 'Matricule;Nom;Prénom;ssType;Début;Fin;Jours;'."\r\n";
				$r=D('LeaveLog')->where($map)->findAll();
			}

			if($_POST['type']=='subordinate'){

				$map=" user_id in ($str)";
				if($_POST['expall']==1&&$_POST['alltype']!='search'){
					$map=$_POST['allmap'];
				}
				if($_POST['decompte']){
					echo 'Matricule;Nom;Prénom;ssType;Début;Fin;Jours;'."\r\n";
					$r=D('LeaveLog')->where($map)->findAll();
				}else{
					echo 'Matricule;Nom;Prénom;ssType;Nombre;Décpte;'."\r\n";
					$r=D('LeaveTotal')->where($map)->findAll();
				}

			}

			if(empty($r)){
				$this->error('Empty!');
			}

			$filename="Export_".date("Y_m_d_H_i_s").".csv";
            header("Content-Type: application/vnd.ms-excel; charset=UTF-8");   
			//header("Content-type:text/x-csv");  
            header("Pragma: public");   
            header("Expires: 0");   
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");   
                         
            //header("Content-Disposition: attachment;filename='".$Filename."'");   
			header('Content-Disposition: attachment; filename="'.$filename.'"');
            header("Content-Transfer-Encoding: binary ");


			if($_POST['type']=="showh"||($_POST['type']=='subordinate'&&!$_POST['decompte'])){
				foreach($r as $v){
					echo $v['user_id'].";".$v['first_name'].";".$v['last_name'].";".$v['type'].";".$v['total'].";".$v['remain'].";".$v['jours'];
					echo "\r\n";
				}
			}

			elseif($_POST['type']=="showlogs"||($_POST['type']=='subordinate'&&$_POST['decompte'])){
				foreach($r as $v){
					echo $v['user_id'].";".$v['first_name'].";".$v['last_name'].";".$v['type'].";".$v['debut'].";".$v['fin'].";".$v['jours'];
					echo "\r\n";
				}
			}

			else{
				foreach($r as $v){
					foreach($v as $k=>$vv){
						if($k!='id'){
							echo $vv.";";
						}
					}
					echo "\r\n";
				}	
			
			}
	}

}
?>